package com.yanqu.road.logcollector.db;

import com.clickhouse.client.ClickHouseException;
import com.clickhouse.client.ClickHouseNode;
import com.clickhouse.client.config.ClickHouseDefaults;
import com.clickhouse.jdbc.ClickHouseDataSource;
import com.yanqu.road.dao.db.DbPool;
import com.yanqu.road.logcollector.config.ClickHouseConfig;
import com.yanqu.road.utils.JsonUtils;
import com.yanqu.road.utils.LogUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.*;
import java.util.Properties;


public class ClickHousePool implements DbPool {

    private static Logger log = LogManager.getLogger(ClickHousePool.class);

    private ClickHouseDataSource dataSource;

    public ClickHousePool(ClickHouseConfig cfg) {
        try {
            log.info("clickhouse cfg:{}", JsonUtils.toJSONString(cfg));

            String url = cfg.getUrl() + cfg.getDatabase();
            Properties properties = new Properties();
            properties.setProperty(ClickHouseDefaults.USER.getKey(), cfg.getUsername());
            properties.setProperty(ClickHouseDefaults.PASSWORD.getKey(), cfg.getPassword());

            dataSource = new ClickHouseDataSource(url, properties);
        } catch (Exception e) {
            log.error("数据库连接池出错:", e);
        }
    }

    @Override
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    @Override
    public String getColDetail(int types, int len) {
        switch (types) {
            case Types.INTEGER:
                return "Int32";
            case Types.TINYINT:
                return "Int8";
            case Types.SMALLINT:
                return "Int16";
            case Types.BIGINT:
                return "Int64";
            case Types.VARCHAR:
                return "String Default ''";
            case Types.BOOLEAN:
                return "Int8";
        }
        return "String Default ''";
    }

    public boolean isMysqlDB() {
        return false;
    }

    public static void main(String[] args) throws Exception {
     /*   String url = "jdbc:clickhouse://10.1.102.211:8123/xq_test";
        String username = "root";
        String password = "yanqu@123";
        Properties properties = new Properties();
        ClickHouseNode server = ClickHouseNode.builder()
                .host(System.getProperty("chHost", "10.1.102.211"))
              //  .port(ClickHouseProtocol.HTTP, Integer.getInteger("chPort", 8123))
                // .port(ClickHouseProtocol.GRPC, Integer.getInteger("chPort", 9000))
                 .port(ClickHouseProtocol.TCP, Integer.getInteger("chPort", 5001))
                .database("xq_test").credentials(ClickHouseCredentials.fromUserAndPassword(
                        System.getProperty("chUser", "root"), System.getProperty("chPassword", "yanqu@123")))
                .build();
        query(server,"xq_table1_dst");*/

        jdbc();

    }

    public static void jdbc() {
        String url = "jdbc:clickhouse://10.1.102.211:8123/xq_test?user=root&password=yanqu@123";
        try {
            //    Class.forName("com.clickhouse.jdbc.ClickHouseDriver");
            Class.forName("ru.yandex.clickhouse.ClickHouseDriver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            Connection conn = DriverManager.getConnection(url, "root", "yanqu@123");
            ResultSet rs = conn.createStatement().executeQuery("SELECT * from xq_table1_dst");
            while (rs.next()) {
                int id = rs.getInt("id");
                String skuId = rs.getString("sku_id");
                System.out.println(id + "    " + skuId);
            }
        } catch (SQLException e) {
            LogUtils.ERROR.error("clickhouse jdbc error:", e);
        }
    }


    static int query(ClickHouseNode server, String table) throws ClickHouseException {
       /* try (ClickHouseClient client = ClickHouseClient.newInstance(server.getProtocol());
             ClickHouseResponse response = client.read(server)
                     // prefer to use RowBinaryWithNamesAndTypes as it's fully supported
                     // see details at https://github.com/ClickHouse/clickhouse-java/issues/928
                     .format(ClickHouseFormat.RowBinaryWithNamesAndTypes)
                     .query("select * from " + table).execute().get()) {
            int count = 0;
            // or use stream API via response.stream()
            for (ClickHouseRecord r : response.records()) {
                count++;
            }
            return count;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw ClickHouseException.forCancellation(e, server);
        } catch (ExecutionException e) {
            throw ClickHouseException.of(e, server);
        }*/
        return 0;
    }
}

